package com.it.myh;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 通过lock锁来解决线程安全问题
 */
class Window implements Runnable{

    private int tickets = 100;
    //1.实例化`ReentrantLock`
    private ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {

        while (true){
            //2.将操作共享数据的代码用`try`包起来
            try {
                //3.调用lock()方法
                lock.lock();
                if (tickets > 0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":票号为:" + tickets);
                    tickets--;
                }else {
                    break;
                }
            }finally {
                //4.在`finally`中调用unlock()方法
                lock.unlock();
            }
        }
    }
}
public class Ev_0216_05 {

    public static void main(String[] args) {
        Window window = new Window();
        Thread thread1 = new Thread(window);
        Thread thread2 = new Thread(window);
        Thread thread3 = new Thread(window);
        thread1.setName("一号窗口");
        thread2.setName("二号窗口");
        thread3.setName("三号窗口");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
